package cn.com.homeyoda.aimate.aihealth.ui.bluetooth;

import android.Manifest;
import android.annotation.SuppressLint;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.StrictMode;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;

import androidx.lifecycle.ViewModelProviders;
import androidx.navigation.fragment.NavHostFragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.afollestad.materialdialogs.MaterialDialog;
import com.airbnb.lottie.LottieDrawable;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.jeremyliao.liveeventbus.LiveEventBus;
import com.wzq.mvvmsmart.utils.ToastUtils;
import com.yasee.yasee.Notify;
import com.yasee.yasee.Yasee;
import com.yasee.yasee.core.configs.BleConfig;
import com.yasee.yasee.core.configs.LogConfig;
import com.yasee.yasee.core.enums.CmdType;
import com.yasee.yasee.core.enums.DeviceProcess;
import com.yasee.yasee.core.enums.NotifyType;
import com.yasee.yasee.core.interfaces.NotifyInterface;
import com.yasee.yasee.core.models.AdvertisementData;
import com.yasee.yasee.core.models.NotifyResp;
import com.yasee.yasee.protocols.ble.BleDevice;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;

import cn.com.homeyoda.aimate.aihealth.BR;
import cn.com.homeyoda.aimate.aihealth.R;
import cn.com.homeyoda.aimate.aihealth.app.AppViewModelFactory;
import cn.com.homeyoda.aimate.aihealth.base.BaseActivity;
import cn.com.homeyoda.aimate.aihealth.bean.FeedbackTypeBean;
import cn.com.homeyoda.aimate.aihealth.databinding.ActivityBluetoothSearchBinding;
import cn.com.homeyoda.aimate.aihealth.databinding.ActivityProblemBinding;
import cn.com.homeyoda.aimate.aihealth.ui.health.VideoPlayActivity;
import cn.com.homeyoda.aimate.aihealth.ui.problem.ProblemAdapter;
import cn.com.homeyoda.aimate.aihealth.ui.problem.ProblemModel;
import cn.com.homeyoda.aimate.aihealth.utils.DeviceManager;
import cn.com.homeyoda.aimate.aihealth.utils.GradientUtils;
import cn.com.homeyoda.aimate.aihealth.utils.JsonFileManager;
import cn.com.homeyoda.aimate.aihealth.utils.PermissionHelper;

import static android.view.ViewGroup.LayoutParams.WRAP_CONTENT;
import static cn.com.homeyoda.aimate.aihealth.utils.AppConstants.FEEDBACK_SUCCESS;

public class BluetoothSearchActivity extends BaseActivity<ActivityBluetoothSearchBinding, BluetoothSearchModel> {

    private BluetoothListAdapter bluetoothListAdapter;
    private BluetoothMatchAdapter bluetoothMatchAdapter;
    private List<BleDevice> rawList;
    private List<BluetoothMatchBean> matchList;

    private static final int REQUEST_IMAGE_CAPTURE = 1;
    private static final int PERMISSIONS_REQUEST_CODE = 100;
    private File photoFile;
    private PermissionHelper permissionManager;
    private String filePath = "bluetoothMatch.json";
    private JsonFileManager jsonFileManager;
    private String mac;//设备编号
    private String model;//设备型号

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
        StrictMode.setVmPolicy(builder.build());
        builder.detectFileUriExposure();
    }

    @Override
    public BluetoothSearchModel initViewModel() {
        AppViewModelFactory factory = AppViewModelFactory.getInstance(getApplication());
        return ViewModelProviders.of(this, factory).get(BluetoothSearchModel.class);
    }

    @Override
    public void initData() {
        super.initData();
        jsonFileManager = new JsonFileManager(this);
        Yasee.getSingle().setContext(getApplicationContext());
        Yasee.getSingle().logConfig = new LogConfig(true,true,true,true);
        permissionManager = new PermissionHelper(BluetoothSearchActivity.this);
        permissionManager.requestPermissions(new PermissionHelper.PermissionCallback() {
            @Override
            public void onPermissionGranted() {
                Toast.makeText(BluetoothSearchActivity.this, "所有权限已授予", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onPermissionDenied(String[] pps) {
                Toast.makeText(BluetoothSearchActivity.this, "以下权限被拒绝: " + pps, Toast.LENGTH_SHORT).show();
            }
        });
        Yasee.getSingle().bleConfig = new BleConfig(5);
        Yasee.getSingle().scan();
        Notify.getSingle().listen(_devices);
        Notify.getSingle().listen(_binds);
        Notify.getSingle().listen(_state);
        initRecyclerView();
    }

    private void initRecyclerView() {
        bluetoothListAdapter = new BluetoothListAdapter(R.layout.bluetooth_list_item, rawList, getApplicationContext());
        binding.setLayoutManager(new LinearLayoutManager(getApplicationContext(), LinearLayoutManager.HORIZONTAL, false));
        binding.setAdapter(bluetoothListAdapter);


        bluetoothListAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @SuppressLint("NonConstantResourceId")
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                BleDevice item = bluetoothListAdapter.getData().get(position);
                if (view.getId() == R.id.link) {
                    Log.i("huahua","连接====");
                    item.connect();
                }
                if (view.getId() == R.id.delete) {
                    Log.i("huahua","删除====");
                    deleteDialog(position);
                }

            }
        });

        bluetoothMatchAdapter = new BluetoothMatchAdapter(R.layout.bluetooth_match_item, matchList, getApplicationContext());
        binding.setLayoutManager1(new LinearLayoutManager(getApplicationContext(), LinearLayoutManager.HORIZONTAL, false));
        binding.setAdapter1(bluetoothMatchAdapter);
        matchList = jsonFileManager.readList(filePath);
        if(matchList.size()>0){
            bluetoothMatchAdapter.setNewData(matchList);
        }

        bluetoothMatchAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @SuppressLint("NonConstantResourceId")
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                BluetoothMatchBean item = bluetoothMatchAdapter.getData().get(position);
                if (view.getId() == R.id.match) {
                    Log.i("huahua","匹配====");
                    String mac = item.getMac();
                    String mode = item.getMode();
                    String result = mode.replaceAll("(-.*)", "");
                    BleDevice bd =  new BleDevice(mac,result+mac.substring(12), new AdvertisementData(new HashMap<>()));
                    bd.connect();
                }


            }
        });


        binding.back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        binding.shuaxin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Yasee.getSingle().setContext(getApplicationContext());
                Yasee.getSingle().bleConfig = new BleConfig(5);
                Yasee.getSingle().scan();
            }
        });

        GradientUtils.setTextGradient(binding.tvSearch, "#0065FF", "#00E1F0");
        binding.animationView.setAnimation("loading.json");
        binding.animationView.loop(true);
        // 设置循环
        binding.animationView.setRepeatCount(LottieDrawable.INFINITE);
        // 播放动画
        binding.animationView.playAnimation();

    }

    private void deleteDialog(int position) {
        MaterialDialog loginDialog = new MaterialDialog.Builder(this)
                .customView(R.layout.dialog_bluetooth_delete, false)
                .show();

        loginDialog.getView().findViewById(R.id.cancel).setOnClickListener(v -> loginDialog.dismiss());
        loginDialog.getView().findViewById(R.id.ok).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                rawList.remove(position);
                bluetoothListAdapter.notifyDataSetChanged();
                loginDialog.dismiss();
            }
        });
        if (loginDialog.getWindow() != null) {
            loginDialog.setCancelable(false);
            loginDialog.setCanceledOnTouchOutside(false);
            loginDialog.getWindow().setWindowAnimations(R.style.DialogAnimation);
            loginDialog.getWindow().setLayout(400, WRAP_CONTENT);
            loginDialog.getWindow().setBackgroundDrawable(new android.graphics.drawable.ColorDrawable(0));
        }
    }

    public static boolean hasCommonValue(List<BleDevice> list1, List<BluetoothMatchBean> list2) {
        return list1.stream().anyMatch(list2::contains);
    }

    NotifyInterface _devices = new NotifyInterface() {
        @Override
        public NotifyType getType() {
            return NotifyType.searchDevices;
        }
        @Override
        public void message(NotifyResp data) {
            Log.i("huahua","searchDevices===="+(List<BleDevice>) data.data);
            rawList = (List<BleDevice>) data.data;
            matchList = jsonFileManager.readList(filePath);
            Log.i("huahua","searchDevices==matchList=="+matchList.size());
            bluetoothListAdapter.setNewData(rawList);
//            if(matchList.size()>0){
//                if(hasCommonValue(rawList,matchList)){
//                    bluetoothMatchAdapter.setNewData(matchList);
//                }else{
//                    bluetoothListAdapter.setNewData(rawList);
//                }
//            }else{
//                bluetoothListAdapter.setNewData(rawList);
//            }

        }
    };

    NotifyInterface _state = new NotifyInterface() {
        @Override
        public NotifyType getType() {
            return NotifyType.deviceLink;
        }
        @Override
        public void message(NotifyResp data) {
            NotifyResp.BleLink bleLink = (NotifyResp.BleLink) data.data;
            if(bleLink.process == DeviceProcess.unlink){
                ToastUtils.showShort("设备连接失败！");
                return;
            }
            Log.i("huahua","bleLink.process===="+bleLink.process);
            Log.i("huahua","deviceLink==111=="+((BleDevice) bleLink.device).state);
            if (bleLink.process == DeviceProcess.rwIsOk){
                mac = ((BleDevice)((NotifyResp.BleLink) data.data).device).getMac();
                model = ((BleDevice)((NotifyResp.BleLink) data.data).device).getModel();
                Log.i("huahua","mac===="+mac);
                Log.i("huahua","model===="+model);
                Log.i("huahua","jsonFileManager===="+jsonFileManager.readList(filePath).toString());
                List<BluetoothMatchBean> matchList = jsonFileManager.readList(filePath);
                boolean result2 = false;
                for(int i= 0;i < matchList.size();i++){
                    Log.i("huahua","getMac===="+matchList.get(i).getMac());
                    if(matchList.get(i).getMac().equals(mac)){
                        result2 = true;
                    }
                }
                Log.i("huahua","result2===="+result2);
                if(!result2){
                    BluetoothMatchBean bean = new BluetoothMatchBean();
                    bean.setMac(mac);
                    bean.setMode(model);
                    jsonFileManager.appendToList(filePath, bean);
                }
                if(!isActivityRunning(BluetoothSuccessActivity.class)){
                    BluetoothDevice bluetoothDevice = ((BleDevice)((NotifyResp.BleLink) data.data).device).amount;
                    Log.i("huahua","bluetoothDevice======"+bluetoothDevice);
                    DeviceManager.getInstance().setCurrentDeviceList(bluetoothDevice);
                    Bundle bundle = new Bundle();
                    bundle.putString("mac", mac);
                    bundle.putString("model", model);

                    startActivity(BluetoothSuccessActivity.class, bundle);
                }

                finish();
                Log.i("huahua","deviceLink==222=="+((BleDevice) bleLink.device).state);
            }

        }
    };


    NotifyInterface _binds = new NotifyInterface() {
        @Override
        public NotifyType getType() {
            return NotifyType.bindDevices;
        }
        @Override
        public void message(NotifyResp data) {
            Log.i("huahua", "message: 绑定变化");
            //MainActivity.binds.addAll((List<BleDevice>) data.data);
//            myAdapter.setItems((List<BleDevice>) data.data);
        }
    };


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
            if (photoFile != null && photoFile.exists()) {
                // cameraList.add(photoFile);
                // cameraAdapter.setNewData(cameraList);
            } else {
                // Handle the case where the file doesn't exist as expected
            }
        }
    }


    @Override
    public void initViewObservable() {
        super.initViewObservable();

        LiveEventBus.get(FEEDBACK_SUCCESS, boolean.class).observe(this, aBoolean -> {
            finish();
        });

    }

    @Override
    public int initContentView(Bundle savedInstanceState) {
        return R.layout.activity_bluetooth_search;
    }

    @Override
    public int initVariableId() {
        return BR.viewModel;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Notify.getSingle().remove(_devices);
        Notify.getSingle().remove(_state);
        Notify.getSingle().remove(_binds);

    }
}
